package com.tticar.invmanager.tticar.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.HttpClientUtil;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.ServiceUtil;
import com.tticar.invmanager.controller.BaseController;
import com.tticar.invmanager.entity.SysTenant;
import com.tticar.invmanager.entity.vo.MyPage;
import com.tticar.invmanager.mapper.WStoreMapper;
import com.tticar.invmanager.service.ISysPictrueService;
import com.tticar.invmanager.service.ISysTenantService;
import com.tticar.invmanager.tticar.entity.*;
import com.tticar.invmanager.tticar.service.*;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;


/**
 * Created by jiwenbin on 2018/10/08
 */
@Controller
@RequestMapping("tticarStore")
public class TTicarStoreController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private final String[] pictureType = {"jpg","jpeg", "png", "gif"};

    // 文件保存地址
    @Value("${oss.url}")
    private String ossUrl;
    // 供应商项目
    @Value("${tticat.supply}")
    private String TTICAT_SUPPLY;

    @Autowired
    ISysTenantService sysTenantService;
    @Autowired
    IStoreOwnerService storeOwnerService;
    @Autowired
    IStoreService storeService;
    @Autowired
    ISysDictValueService sysDictValueService;
    @Autowired
    IGoodsBrandService goodsBrandService;
    @Autowired
    ISysPictrueService sysPictrueService;
    @Autowired
    IPicturesService picturesService;
    @Autowired
    private WStoreMapper wStoreMapper;


    @GetMapping
    public String index(ModelMap modelMap) {
        SysTenant tenant = sysTenantService.selectById(ServiceUtil.getLoginUser().getTenantId());
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("mobile", tenant.getMobile());
        com.tticar.invmanager.tticar.entity.StoreOwner storeOwner = storeOwnerService.selectOne(wrapper);
        if (storeOwner != null) {
            modelMap.put("storeOwner", storeOwner);
        }
        return "/tticar/store/store";
    }

    @GetMapping("list")
    @ResponseBody
    public Page list(Store store, MyPage<Store> page) {
        // 根据当前用户租户的手机号匹配天天爱车店铺
//        if (store.getStoreOwnerId() == null || store.getStoreOwnerId() == 0) {
//            return null;
//        }
//        Wrapper w = new EntityWrapper<>();
//        w.eq("storeOwnerId",  store.getStoreOwnerId());
//        if (StringUtils.isNoneBlank(store.getName())) {
//            w.andNew().like("name", store.getName()).or().like("tel", store.getName());
//        }
        List<Long> longs = wStoreMapper.queryStoreBelongUser();
        if (longs == null || longs.size() < 1) {
            return null;
        }
        Wrapper w = new EntityWrapper<>();
        w.in("id", longs);
        if (StringUtils.isNoneBlank(store.getName())) {
            w.andNew().like("name", store.getName()).or().like("tel", store.getName());
        }
        return storeService.selectPage(page, w);
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(storeService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(Store store, ModelMap modelMap) {
        modelMap.put("id", store.getId());
        if (store.getId() != null && store.getId() != 0) {
            // 查询店铺的图片
            Wrapper wrapper = new EntityWrapper<>();
            wrapper.eq("refId", store.getId());
            List<Pictures> picturesList = picturesService.selectList(wrapper);
            List<String> pictureUrlList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(picturesList)) {
                for (Pictures picture : picturesList) {
                    pictureUrlList.add(ossUrl + picture.getPath());
                }
            }
            modelMap.put("pictureUrlList", pictureUrlList);
            System.out.println("图片链接：" + pictureUrlList.toString());
        }
        return "/tticar/store/edit";
    }

    /**
     * 注册店铺短信验证码
     * @param tel
     * @return
     */
    @GetMapping("getSmsCode")
    @ResponseBody
    public MyResponseBody getSmsCode(@RequestParam("tel") String tel ) {
        MyResponseBody responseBody = MyResponseBody.success();
        String url = TTICAT_SUPPLY+"/sms/sendCaptcha";
        Map<String, String> map = new HashMap<>();
        map.put("typecode", "400");
        map.put("mobiles", tel);
        String result = HttpClientUtil.sendHttpPost(url, map);
        logger.info("仓储系统注册店铺发送短信验证码,手机号{},结果：{}",tel, result);
        return responseBody;
    }

    /**
     * 注册店铺信息
     * @param registerRequest
     * @return
     */
    @RequestMapping("register")
    @ResponseBody
    public MyResponseBody register(StoreRegister registerRequest) throws Exception {
        // 上传图片
        List<String> urlList = uploadPicture(registerRequest.getFiles());
        registerRequest.setStoreImages(urlList.toString());

        // 注册
        registerRequest.setType(1); // 0 店铺 1 供应商
        registerRequest.setFiles(null);
        logger.info("注册店铺信息：{}", JSON.toJSONString(registerRequest));
        MyResponseBody responseBody = MyResponseBody.success();
        String url = TTICAT_SUPPLY+"/store/user/register/nofile";
        Map param = JSON.parseObject(JSON.toJSONString(registerRequest));
        String result = HttpClientUtil.sendHttpPost(url, param);
        logger.info("注册店铺结果：{}", result);
        Map map = JSON.parseObject(result);
        if (!(boolean)map.get("success")) {
            throw new MyServiceException("操作失败："+map.get("msg"));
        }
        return responseBody;
    }

    /**
     * 修改店铺信息
     * @param store
     * @return
     */
    @PostMapping("update")
    @ResponseBody
    public MyResponseBody update(Store store) throws Exception {
        //供应商端法人姓名、法人身份证照片、营业执照,名称审核后不能更改
        StoreOwner storeOwner = storeOwnerService.selectById(store.getStoreOwnerId());
        if (storeOwner.getCompanyNameCheck() == 1 && store.getFiles().length > 0) {
            throw new MyServiceException("审核后不能更改店铺图片");
        }
        // 上传图片
        List<String> urlList = uploadPicture(store.getFiles());
        for (String url : urlList) {
            Pictures pictures = new Pictures();
            pictures.setPath(url);
            pictures.setRefId(store.getId());
            pictures.setType(2);
            pictures.setCtime(new Date());
            picturesService.insert(pictures); // 保存图片路径
        }
        store.setType(1);
        storeService.updateById(store);
        return MyResponseBody.success();
    }

    private List<String> uploadPicture(MultipartFile[] files) throws Exception {
        // 上传图片
        List<String> urlList = new ArrayList<>();
        if (pictureType.length > 5) {
            throw new MyServiceException("最多可以上传5张图片");
        }
        for (int i=0; i<files.length; i++) {
            if (files[i] == null) continue;
            String fileName = files[i].getOriginalFilename();
            String fileType = fileName.substring(fileName.lastIndexOf(".")+1);

            for (int j=0; j<=pictureType.length; j++) {
                if (j == pictureType.length) {
                    throw new MyServiceException("请上传正确的图片格式,支持格式（jpg, jpeg, png, gif）");
                }
                if(pictureType[j].equalsIgnoreCase(fileType)) {
                    break;
                }
            }

            String url = sysPictrueService.upload(files[i], "editstore/store/");
            urlList.add(url);
        }
        return  urlList;
    }

    /**
     * 经营范围
     * @return
     */
    @GetMapping("mgrScope")
    @ResponseBody
    public List mgrScope() {
        return sysDictValueService.selectSysDictValueList("mgr_scope");
    }

    /**
     * 店内说明
     * @return
     */
    @GetMapping("comment")
    @ResponseBody
    public List comment() {
        return sysDictValueService.selectSysDictValueList("store_comment");
    }

    /**
     * 优惠政策
     * @return
     */
    @GetMapping("preferential")
    @ResponseBody
    public List preferential() {
        return sysDictValueService.selectSysDictValueList("charge_policy");
    }

    /**
     * 品牌
     * @return
     */
    @GetMapping("mgrBrands")
    @ResponseBody
    public Page mgrBrands(GoodsBrand goodsBrand, MyPage<GoodsBrand> page) {
        return goodsBrandService.selectPage(goodsBrand, page);
    }

    /**
     * 店铺授权页面跳转
     * */
    @GetMapping("authorization")
    public String authorization() {
        return "/tticar/store/store_authorization";
    }

    /**
     * 店铺提交验证
     * */
    @PostMapping("authorizationSubmit")
    @ResponseBody
    public MyResponseBody authorizationSubmit(@RequestParam("phoneNum") Long phoneNum,@RequestParam("password") String password) {
        MyResponseBody responseBody = MyResponseBody.success();
        storeOwnerService.verifyUser(phoneNum,password);
        return responseBody;
    }

    /**
     * 取消店铺授权
     * */
    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
//        storeService.deleteBatchIds(ids);
        wStoreMapper.cancelRelative(id);
        return responseBody;
    }
}
